package controllers

import (
	"errors"
	"meituan/apps/common/models"
	db2 "meituan/db"
	"meituan/utils/response"
	"strconv"

	"github.com/gin-gonic/gin"
)

func ListBanner(ctx *gin.Context) {
	banners := make([]models.Banner, 20)
	db, _ := db2.NewDB()
	defer db.Close()
	db.Table("banners").Find(&banners)
	ctx.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": banners,
	})
}

func DeleteBanner(ctx *gin.Context) {
	id := ctx.Param("id")
	_, e := strconv.Atoi(id)
	if e != nil {
		response.SendError(ctx, errors.New("未找到对象"), 404)
		return
	}
	db, _ := db2.NewDB()
	defer db.Close()
	db.Table("banners").Where("id = ?", id).Delete(&models.Banner{})
	ctx.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}

func UpdateBanner(ctx *gin.Context) {
	id := ctx.Param("id")
	numberId, e := strconv.Atoi(id)
	if e != nil {
		response.SendError(ctx, errors.New("未找到对象"), 404)
		return
	}
	banner := models.NewBanner()
	banner.ID = uint(numberId)
	e = ctx.ShouldBindJSON(banner)
	if e != nil {
		response.SendError(ctx, e, 400)
		return
	}
	db, _ := db2.NewDB()
	defer db.Close()
	db.Model(banner).Update(banner)
	ctx.JSON(200, gin.H{
		"code": 200,
		"msg":  "修改成功",
		"data": banner,
	})
}

func AddBanner(ctx *gin.Context) {
	banner := models.NewBanner()
	e := ctx.ShouldBindJSON(banner)
	if e != nil {
		response.SendError(ctx, e, 400)
		return
	}

	db, _ := db2.NewDB()
	defer db.Close()
	db.Table("banners").Save(banner)
	ctx.JSON(200, gin.H{
		"code": 200,
		"msg":  "新建成功",
		"data": banner,
	})

}
